/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedLineData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import { canCurvesFormClosedLoop } from '@app-base/common/utils/lines-coplanar';

type Params = {
  profile: string[];
};

/**
 * 轮廓面
 *
 * - 选中一条或多条曲线，创建一个轮廓面
 * - 若弹窗包含一个及以上的输入对象，则应保证完成键可点击。
 *  即 前端做个初步的判断，但是不禁止用户去后台做更精确的判断
 */
function CmdMface({ title, onClose, props }: CurvedCmdDialogParams) {
  const [formData, setFormData] = useState<pickedLineData[]>([]);

  const schema: RJSFSchema = {
    type: 'array',
    items: {
      type: 'string',
      enum: [],
    },
    format: PickInputRJSFFormat.MultiPickCurve,
    uniqueItems: true,
  };

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props != null) {
      const params: Params = props.params;
      const { profile } = params;

      await initEditDependency(profile);

      setFormData(
        profile.map(
          (face) => picker.generatePickObjByPickID(face) as pickedLineData,
        ),
      );
    }
  }, []);

  const isFormDataValid = () =>
    formData.length >= 1 && formData.every((c) => c != null);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute();
    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-mface', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateMface',
      editDxid: props?.shape,
    });

  const execute = async (preview = false) => {
    const params = {
      profile: formData.map((i) => i.edgeId),
    };

    confirmCommand(
      {
        a: params,
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }

    // 做个初步的判断(粗略的判断)
    // - 若不满足闭合环的条件，则不执行预览
    // - TODO：后续可以做个粗略的共面判断
    const points = formData.map((c) => c.edgeData);
    if (!canCurvesFormClosedLoop(points, 1e-3)) {
      return;
    }

    await execute(true);
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      onChange={(v) => {
        setFormData(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        'ui:placeholder': '请输入边界曲线',
        'ui:autofocus': true,
      }}
      formData={formData}
      isFormDataValid={isFormDataValid()}
      noValidate
    />
  );
}

export const cmdMface: CurvedBaseCommand = {
  id: 'CmdMface',
  label: 'command.mface',
  icon: 'commands/curved/mface',
  help: {
    remark: 'tips.redo',
  },
  create: (label, onClose, props) => (
    <CmdMface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
